﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;
using ZX.Aspose;
using log4net;

namespace ZX.EHR.Web
{
    public partial class hrImportBalanceTime : BasePage
    {
        static string resFileName = "";
        string flag = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            flag = this.GetStringFromQueryString("flag", "");
            if (flag.Trim() == "save")
            {
                this.SaveData();
            }
        }


        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            try
            {
                if (!uploadedFile.IsValid)
                    return string.Empty;

                FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
                string path = Request.PhysicalApplicationPath + "upload\\EHR\\";
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                resFileName = path + fileInfo.Name;
                uploadedFile.SaveAs(resFileName);

                RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
                string fileLabel = fileInfo.Name;
                string fileLength = uploadedFile.ContentLength / 1024 + "K";
                return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
            }
            catch (Exception ex)
            {
                return "";
            }
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData()
        {
            /// <summary>
            /// 所有上传数据
            /// </summary>
            IList<DataTable> lstImportData = null;
            try
            {
                //读取EXCEL
                //string resFileName = Request.PhysicalApplicationPath + "upload/EHR/" + fileName;
                if (resFileName != "")
                {
                    lstImportData = new List<DataTable>();
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);

                    if (dtExcel != null && dtExcel.Rows.Count > 0)
                    {
                        lstImportData.Add(dtExcel);
                    }

                    if (lstImportData.Count > 0)
                    {
                        DbSql dbsql = new DbSql();
                        string flowType = "BALANCETIME";//OVERTIME-加班，BALANCETIME-结算
                        string insertSql = @"insert into wkOvertimeLeave(id,employeeID,FlowType,FlowEndTime,BeginTime,EndTime,RemTime,
                                            WorkDayOverTime,WeekendOverTime,HolidayOverTime,TotalOverTime,JiabanShiYou) 
                                            values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}') ";
                        string delSql = @"delete from wkOvertimeLeave where employeeID='{0}' and FlowType='{1}' and BeginTime='{2}' and EndTime='{3}' ";
                        int i = 0;
                        string employeCode = "", employeeID = "", employeeName = "", JiabanShiYou = "";
                        DateTime beginTime = new DateTime();
                        DateTime endTime = new DateTime();
                        DateTime flowEndTime = new DateTime();
                        decimal remTime = 0, workDayOverTime = 0, weekendOverTime = 0, holidayOverTime = 0, totalOverTime=0;

                        foreach (DataTable dt in lstImportData)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                beginTime = new DateTime();
                                endTime = new DateTime();
                                flowEndTime = new DateTime();
                                remTime = 0;
                                workDayOverTime = 0;
                                weekendOverTime = 0;
                                holidayOverTime = 0;
                                totalOverTime = 0;
                                JiabanShiYou = "";
                                flowType = "";

                                employeCode = dr["员工编号"].ToString().Trim();
                                flowType = dr["流程类型"].ToString().Trim();
                                DateTime.TryParse(dr["归档日期"].ToString().Trim(), out flowEndTime);
                                DateTime.TryParse(dr["开始时间"].ToString().Trim(), out beginTime);
                                DateTime.TryParse(dr["结束时间"].ToString().Trim(), out endTime);

                                if (flowType == "" || employeCode == "" || flowEndTime ==DateTime.MinValue || beginTime == DateTime.MinValue || endTime == DateTime.MinValue)
                                {
                                    continue;
                                }

                                if (flowType == "加班")
                                {
                                    flowType = "OVERTIME";
                                    JiabanShiYou = dr["加班事由"].ToString().Trim();
                                    decimal.TryParse(dr["工作日加班"].ToString().Trim(), out workDayOverTime);
                                    decimal.TryParse(dr["节假日加班"].ToString().Trim(), out weekendOverTime);
                                    decimal.TryParse(dr["法定假加班"].ToString().Trim(), out holidayOverTime);
                                    totalOverTime = workDayOverTime + weekendOverTime + holidayOverTime;
                                }
                                else if (flowType == "结算")
                                {
                                    flowType = "BALANCETIME";
                                    decimal.TryParse(dr["结算时长"].ToString().Trim(), out remTime);
                                }

                                Dictionary<string, string> dicEmpInfo = GetEmpInfos(employeCode);
                                if (dicEmpInfo.Count > 0)
                                {
                                    employeeID = dicEmpInfo["EmployeeID"];
                                    employeeName = dicEmpInfo["EmployeeName"];
                                    dbsql.ExecuteSql(string.Format(delSql, employeeID, flowType, beginTime, endTime));
                                    dbsql.ExecuteSql(string.Format(insertSql, Guid.NewGuid().ToString(), employeeID, flowType, flowEndTime, beginTime, endTime, remTime, workDayOverTime, weekendOverTime, holidayOverTime, totalOverTime,JiabanShiYou));
                                    i++;
                                }
                            }
                        }
                        HttpContext.Current.Response.Write("1|" + i.ToString() + "|OK");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("读取EXCEL为空,请检查文件,可能Sheet未命名为Sheet1或没有数据!");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("文件未上传");//文件未上传
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);//出错了
                throw;
                //var logger = LogManager.GetLogger(GetType());
                //logger.Error(ex.Message, ex);
            }
            finally
            {
                if (lstImportData != null)
                {
                    lstImportData.Clear();
                }
                resFileName = "";
            }
        }

        /// <summary>
        /// 根据导入的员工编号，匹配员工信息
        /// </summary>
        /// <param name="employeCode">员工编号</param>
        /// <returns></returns>
        protected Dictionary<string, string> GetEmpInfos(string employeCode)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("EmployeeCode='{0}'", employeCode);
            ZX.EHR.Library.hrEmployee hrEmployee = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            if (hrEmployee != null)
            {
                dic.Add("EmployeeID", hrEmployee.ID.ToString());
                dic.Add("EmployeeCode", hrEmployee.EmployeeCode);
                dic.Add("EmployeeName", hrEmployee.CName);
            }
            return dic;
        }
    }
}